//
//  AuthManager.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/3/30.
//

import Foundation
import ThingSmartUtil
import ThingSmartHomeKit

final class AuthManager: ObservableObject {
    static let shared = AuthManager()
    
    // 是否已经登录和2个因素有关：1，钥匙串有保存token，
    @Published  private(set) var isLoggedIn: Bool = false
    @Published  private(set) var istuyaLogin: Bool = false

    var userInfo:  HomeAPI.UserInfo.Response?

    
    
    private let tokenKey = "Authorization"
    private let appInstallKey = "appInstallID"
    private let appleUserIdKey = "apple_user_id" // 苹果授权返回的userid
    private let wechatCodeKey = "wechat_code" // 微信授权 code
    private let wechatStateKey = "wechat_state" // 微信授权 state
    
    private init() {
        let _ = getToken() // 为了正确初始化isLoggedIn
        guard UserDefaults.standard.string(forKey: appInstallKey) != nil else {
            // 安装后第一次打开，会生成一个新的ID存入，同时删除Token，表明未登陆状态
            let installID = UUID().uuidString
            UserDefaults.standard.set(installID, forKey: appInstallKey)
            logout()
            return
        }
    }

    func tuyaLogined() {
        DispatchQueue.main.async {
            self.istuyaLogin = ThingSmartUser.sharedInstance().isLogin
        }
    }
    // 保存Token
    func saveToken(_ token: String) {
        setLoggedIn(true)
        KeychainManager.save(value: token, key: tokenKey)
    }
    
    func saveAppleUserId(_ userId: String)
    {
        KeychainManager.save(value: userId, key: appleUserIdKey)
    }
    
    func saveWeChatAuthInfo(code: String, state:String)
    {
        KeychainManager.save(value: code, key: wechatCodeKey)
        KeychainManager.save(value: state, key: wechatStateKey)
    }
    
    func getWeChatAuthInfo(code: String, state:String) -> WechatAuthResult?
    {
        if let code = KeychainManager.get(forKey: wechatCodeKey) as? String ,
            let state = KeychainManager.get(forKey: wechatStateKey) as? String
        {
            return WechatAuthResult(socialCode: code, socialState: state)
        }
        return nil
    }

    // 获取Token
    func getToken() -> String? {
        if let token = KeychainManager.get(forKey: tokenKey) as? String
        {
            setLoggedIn(true)
            return token
        }
        setLoggedIn(false)
        return nil
    }
    
    func eraseToken() {
        setLoggedIn(false)
        KeychainManager.erase(key: tokenKey)
    }

    // 退出登录(删除Token)
    func logout() {
        KeychainManager.erase(key: tokenKey)
        setLoggedIn(false)
    }
    
    private func setLoggedIn(_ value: Bool)
    {
        DispatchQueue.main.async {
            self.isLoggedIn = value
        }
    }
}
